
var id = null;
var balance = null;
var token = null;
var outputCount = 0;

const MAX_OUTPUT_COUNT = 10;

var userRef = new Firebase('https://swagmoney.firebaseio.com/');
var auth = new FirebaseSimpleLogin(userRef, function(error, user) {
	if (error) {
		alert(error);
	} else if (! user) {
		// User is not authenticated -> send back to index.html
	} else {
		console.log('Logged in!');
		id = user.id;
		readData();
	}
});

function testFirebase() {
	$.ajax
	({
		type: "POST",
		url: "action.php",
		data: {
			action: 'sendMoney',
			token: token,
			value: 0.01,
			id: id,
			receiverID: '2' // Testing value for now
		},
		cache: false,
		success: function()
		{
			console.log("Order Submitted");
		}
	});
}

function mine() {
	$('#mineDump').load('mine.php', {id: id, token: token}, function(response, status, xhr) {
		if (status == "error") {
			// Usually error code 500 -> signals PHP connection timeout
			console.log(xhr.status);

			// Continue mining
			mine();
		}
		else {
			// Only log output every 10 attempts if nothing is mined
			if (response == false) {
				var loopHTML = '<p>Mining';
				outputCount++;
				for (var i=0; i<outputCount; i++) {
					loopHTML += '.';
				}
				loopHTML += '</p>';
				$('#mineLoop').html(loopHTML);
				if (outputCount == MAX_OUTPUT_COUNT) outputCount = 0;
			} else {
				$('#mineOutput').append(response);
			}

		}
		mine();
	});

}

function create() {
	var email = "test@test.com";
	var password = "123";
	var confirmPassword = "123";

	// Reject user if passwords do not match
	if (password != confirmPassword) {
		alert('Passwords do not match!');
		return;
	}

	// Create user and refresh page so they may login
	auth.createUser(email, password, function(error, user) {
		if (error) {
			alert(error);
		} else {
			// Create a new supervisor
			var supervisor = {};
			supervisor.scripts = [];
			supervisor.id = user.id;

			// Sync supervisor with Firebase
			var supervisorRef = new Firebase('https://swagmoney.firebaseio.com/users/' + user.id);
			supervisorRef.set(supervisor);

			// Redirect user so they may log in
			alert("Account created! You may now login.");
		}
	});
}

function login() {
	var email = "test@test.com";
	var password = "123";

	// Authenticate the user with Firebase
	auth.login('password', {
		email: email,
		password: password,
		rememberMe: true
	});
}

function generateUUID() {
	// RFC4122 Version 4 Implementation
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
		return v.toString(16);
	});
}

function readData() {
	// Reads necessary data for money transfer; only authorized users
	// may ever read from Firebase
	var testRef = new Firebase('https://swagmoney.firebaseio.com/users/' + id);
	testRef.on('value', function(snapshot) {
		var user = snapshot.val();
		balance = user.balance;
		token = user.token;
		console.log("Your new balance is: " + balance);
	});
}

function writeToFirebase() {
	var testRef = new Firebase('https://swagmoney.firebaseio.com/users/' + id);
	testRef.set({balance: 0, userid: id, token: generateUUID(), username: 'test'});
}